<?php
/**
 * 功能描述：	系统设置
 * @module		Controllers
 * @datetime	2022-07-21
 * @version   	v1.0
 * @author   	ZHL
 * @copyrigh  	2022 zhl 版权所有
 */

include SYS_PATH.'extend/ManageDB.php';
class Admin_SystemController extends Controller {

    // 是否登录
    function __construct($controller, $action) {
        parent::__construct($controller, $action);
        $loginSer = new Admin_LoginServe();
        $loginSer->judgeSessionLogin($controller, $action);
    }

    /**
     * @fun		基础配置-页面
     * @desc	获取app文件的内容
     * @date	2022-07-21
     */
    public function index(){
        $sysSer = new Admin_SystemServe;
        $res = $sysSer->getAppConfigInfo();
        // 用户权限信息
        $powerSer = new Admin_PowerServe();
        $powerInfo = $powerSer->getUserPowerInfo();
        // 映射
        $this->set('powerInfo', $powerInfo);
        $this->set('userLevel', getUserLevel());
        $this->set('res', $res);
        $this->set('title', '系统配置');
        $this->set('navde', __FUNCTION__);
        $this->display('sysset');
    }

    /**
     * Notes:基础配置_保存_修改app文件的内容
     * User: ZhuHaili
     * Desc: json - flag ? N : Y
     */
    public function syssave(){
        $param = Fun::input();
		$sysSer = new Admin_SystemServe;
		$hint = $sysSer->updateAppConfig($param);
        delDir(SYS_STILL_PATH);
		Fun::json($hint, true);
	}

	/**
	 * @fun		数据库管理-页面
	 * @date	2018-10-31
	 */
    public function sysdb(){
        $sysSer = new Admin_SystemServe();
        $dbFile = $sysSer->sysDBFile();
        $play['title'] = '数据库管理';
        $play['sqlFile'] = $dbFile;
        $play['result'] = $sysSer->sysDBTables();
        $play['userLevel'] = getUserLevel();
        foreach($play as $k=>$v){
            $this->set($k, $v);
        }
        $this->set('navde', __FUNCTION__);
        $this->display();
	}
	
	/**
	 * @fun		数据库备份
	 * @desc	生成sql文件
	 * @date	2018-10-31
	 */
    public function backupdb(){
        $tables = Fun::input('tables');
        $sysSer = new Admin_SystemServe();
        $sysSer->backupDB($tables);
        $this->set('title', '数据备份');
        $this->set('navde', __FUNCTION__);
	}
	
	/**
	 * @fun		数据库还原
	 * @desc	生成sql文件导入到数据库
	 * @date	2018-10-31
	 */
    public function restoredb(){
        $filedb = Fun::input('filedb');
        $sysSer = new Admin_SystemServe();
        $result = $sysSer->restoreDB($filedb);
        if(is_string($result)){
            htmlAlert($result, SYS_URL_PATH('admin_system_sysdb'));
        }
        $this->set('title', '数据还原');
        $this->set('navde', __FUNCTION__);
	}

    /**
     * Notes:sql命令
     * User: ZhuHaili
     * Date: 2022/9/7
     */
	public function dbdo(){
        $subFlag = isset($_POST['subFlag']) ? $_POST['subFlag'] : 'N';
        $sql = isset($_POST['sqlcode']) ? $_POST['sqlcode'] : '';
        $sysSer = new Admin_SystemServe();
        $result = $sysSer->dbToDo($sql, $subFlag);
        // 用户权限信息
        $powerSer = new Admin_PowerServe();
        $powerInfo = $powerSer->getUserPowerInfo();
        $this->set('powerInfo', $powerInfo);
        $this->set('userLevel', getUserLevel());
        $this->set('sqlcode', $sql);
        $this->set('result', $result);
        $this->set('title', '数据命令');
        $this->set('navde', __FUNCTION__);
        $this->display();
    }

    /**
     * Notes:文件清理
     * User: ZhuHaili
     * Date: 2022/12/6
     */
    public function clear(){
        // 用户权限信息
        $powerSer = new Admin_PowerServe();
        $powerInfo = $powerSer->getUserPowerInfo();
        $this->set('powerInfo', $powerInfo);
        $this->set('userLevel', getUserLevel());
        $this->set('title', '文件清理');
        $this->set('navde', __FUNCTION__);
        $this->display();
    }

    /**
     * Notes:清理文件
     * User: ZhuHaili
     * Date: 2022/12/7
     */
    public function cleardo(){
        $clearflag = Fun::input('clearflag');   // 1 安全清理，2深度清理
        $operate = Fun::input('operate');       // 1 执行清理，2查看进度
        if($operate == 1){
            file_put_contents(SYS_CLEAR_LOG_FILE, 0); // 初始进度
            // 异步清理文件
            $url = SYS_URL_PATH("c_common_clearfile/flag/$clearflag/operate/$operate");
            httpGet($url,1);
            //register_shutdown_function(array($this, 'clearfile')); // 异步处理
        }
        // 读取进度
        $rate = 0;
        if(file_exists(SYS_CLEAR_LOG_FILE)){
            $rate = file_get_contents(SYS_CLEAR_LOG_FILE);
        }

        // 返回数据
        $result['code'] = $rate == 100 ? 10000 : 10001;
        $result['rate'] = $rate;
        Fun::json($result, true);
    }

    /**
     * Notes:静态管理
     * User: ZhuHaili
     * Date: 2023/2/22
     */
    public function still(){
        SYS_ADD_PATH(SYS_STILL_PATH);
        $fileArr = $this->getDir(SYS_STILL_PATH);
        $powerSer = new Admin_PowerServe();
        $powerInfo = $powerSer->getUserPowerInfo();
        $this->set('powerInfo', $powerInfo);
        $this->set('userLevel', getUserLevel());
        $this->set('title', '文件清理');
        $this->set('navde', __FUNCTION__);
        $this->set('fileArr', $fileArr);
        $stillFlag = isset($GLOBALS['ADMIN']['still_flag']) ? $GLOBALS['ADMIN']['still_flag'] : 2;
        $this->set('stillFlag', $stillFlag);
        $this->display();
    }

    /**
     * Notes: 获取静态文件
     * @param $dir
     * @return array
     */
    private function getDir($dir){
        $files = array();
        $this->searchDir($dir, $files);
        return $files;
    }

    /**
     * Notes: 查询静态文件
     * @param $path
     * @param $files
     */
    private function searchDir($path,&$files){
        if(is_dir($path)){
            $opendir = opendir($path);
            while ($file = readdir($opendir)){
                if($file != '.' && $file != '..'){
                    $this->searchDir($path.'/'.$file, $files);
                }
            }
            closedir($opendir);
        }
        if(!is_dir($path)){
            $path = str_replace(array('///','//'),'/',$path);
            $pataArr = explode('tpl/',$path);
            $files[] = SYS_HOST.$pataArr[1];
        }
    }

    /**
     * Notes: 删除静态缓存
     * User: ZhuHaili
     */
    public function delstill(){
        delDir(SYS_STILL_PATH);
        Fun::json('Y', true);
    }

    /**
     * Notes: 指定链接生成静态文件
     * User: ZhuHaili
     */
    public function setonestill(){
        $urlname = Fun::input('urlname');

        $cachePathFix = $GLOBALS['ADMIN']['web_temp_p'];
        if($cachePathFix){
            $fileStill = new CacheHtml(SYS_STILL_PATH.$cachePathFix.'/', SYS_HOST, SYS_URL_FIX);
            $fileStill->urlfilecreate($urlname,'/'.SYS_URL_FIX_STILL.'/1'.SYS_URL_FIX);
        }
        if($GLOBALS['ADMIN']['web_temp_flag'] == 1){
            if($GLOBALS['ADMIN']['web_temp_m']){
                $cachePathFix = $GLOBALS['ADMIN']['web_temp_m'];
                $fileStill = new CacheHtml(SYS_STILL_PATH.$cachePathFix.'/', SYS_HOST, SYS_URL_FIX);
                $fileStill->urlfilecreate($urlname,'/'.SYS_URL_FIX_STILL.'/1/'.SYS_URL_FIX_PORT.'/2'.SYS_URL_FIX);
            }
        }
        Fun::json(array('code'=>'10000','msg'=>'执行成功'), true);
        //htmlAlert('执行成功', SYS_URL_PATH('admin_system_still'));
    }

    /**
     * Notes: 生成静态文件
     * User: ZhuHaili
     */
    public function setstill(){
        $flag = Fun::input('flag');
        $operate = Fun::input('operate');       // 1 执行，2查看进度
        if($operate == 1){
            file_put_contents(SYS_CACHE_LOG_FILE, 0); // 初始进度
            // 异步处理
            $url = SYS_URL_PATH("c_common_stilldo/flag/$flag");
            httpGet($url,1);
        }
        // 读取进度
        $rate = 0;
        if(file_exists(SYS_CACHE_LOG_FILE)){
            $rate = file_get_contents(SYS_CACHE_LOG_FILE);
        }

        // 返回数据
        $result['code'] = $rate == 100 ? 10000 : 10001;
        $result['rate'] = $rate;
        Fun::json($result, true);
    }

    /**
     * Notes:日志文件
     * User: ZhuHaili
     * Date: 2023/6/1
     */
    public function logs(){
        $path = Fun::input('path');
        $paths = SYS_PATH.'runtime/'.$path;
        $files = @scandir($paths);
        if(!$files){
            htmlAlert('没有日志文件', SYS_URL_PATH('admin_system_logs'),3);
        }
        echo "<style> *{font-size:14px;}a{text-decoration: none;}.reda{color:red;}</style>";
        $flag = false;
        foreach(array_reverse($files) as $v){
            if($v != '.' && $v != '..'){
                $flag = true;
                $url = SYS_URL_PATH("admin_system_logs/path/$v");
                $item = "<div><a href='$url'>$v</a></div>";
                if(strpos($v,'.') !== false){
                    $file = $path ? $path.'/'.$v : $v;
                    $down = SYS_LINK.'runtime/'.$file;
                    $file = $path ? $path.'|'.$v : $v;
                    $url = SYS_URL_PATH("admin_system_logshow/file/$file");
                    $del = SYS_URL_PATH("admin_system_logdel/file/$file");
                    $item = "<div><a href='$url'>$v</a> --- <a href='$del' class='reda'>删</a> --- <a href='$down' class='reda' target='_blank'>下</a></div>";
                }
                echo $item;
            }
        }
        if(!$flag){
            htmlAlert('没有日志文件', SYS_URL_PATH('admin_system_logs'),3);
        }
    }

    /**
     * Notes:查看日志
     * User: ZhuHaili
     * Date: 2023/4/25
     */
    public function logshow(){
        $file = Fun::input('file');
        $file = str_replace('|','/',$file);
        $file = SYS_PATH.'runtime/'.$file;
        if(!$file || !file_exists($file)){
            htmlAlert('没有找到文件');
        }
        $myfile = fopen($file, "r") or htmlAlert("无法打开文件！");
        $size = filesize($file);
        if(!$size){
            htmlAlert('文件暂无内容');
        }
        $text = fread($myfile, $size);
        fclose($myfile);
        $txts = array_reverse(explode("|-|",$text));
        echo "<style> *{font-size:12px;} </style>";
        foreach($txts as $txtStr){
            $txtArr = explode("\n",$txtStr);
            foreach($txtArr as $v){
                //echo "<div>$v</div>";
                $k = explode(" ",$v);
                echo '<div>';
                foreach($k as $n){
                    echo '&nbsp;'.htmlentities($n);
                }
                echo '</div>'.PHP_EOL;
            }
        }
    }

    /**
     * Notes:删除文件
     * User: ZhuHaili
     * Date: 2023/6/1
     */
    public function logdel(){
        $file = Fun::input('file');
        $file = str_replace('|','/',$file);
        $file = SYS_PATH.'runtime/'.$file;
        if(!$file || !file_exists($file)){
            htmlAlert('没有找到文件', SYS_URL_PATH('admin_system_logs'),3);
        }
        @unlink($file);
        htmlAlert('删除成功', SYS_URL_PATH('admin_system_logs'),3);
    }
}